<?php

namespace App;

use Session;
use Illuminate\Database\Eloquent\Model;
use DB;
class Admin extends Model
{
    public function getOnes($admin_name){
    	$adminDataOne = DB::table('admin')->where('admin_name',$admin_name)->first();
    	return $adminDataOne;
    }
    //插入登录的时间和次数
	public function login_up($data,$admin_id){
		$res = DB::table('admin')->where('admin_id',$admin_id)->update($data);
		return $res;
	}
	 //管理员展示  分页
    public function lists(){
       return $info= DB::table('admin')->paginate(10);
    }

    //添加管理员
    public function add($data){
        $info = [
        'admin_name'=>$data['admin_name'],
        'admin_password'=>md5($data['admin_password']),
        'add_time'=>time(),
        'email'=>$data['email'],
        'status'=>$data['status']
        ];  
        return DB::table('admin')->insert($info);

    }

    //删除管理员 修改状态值
    public function del($admin_id){
       return  DB::table('admin')->where('admin_id',$admin_id)->update(['status'=>0]);
    }

   
   //管理员 修改状态值
   public function back($admin_id){
       return DB::table('admin')->where('admin_id',$admin_id)->update(['status'=>1]);

   }

   //分配权限列表
   public function SetNode($admin_id){
        
        //查出所有的权限
        $nodelist=DB::table('node')->get();
        $nodelist = array_map('get_object_vars', $nodelist);
       
         //查询关联表里当前管理员下所有的权限id    
       $node_id=DB::table('admin_node')->where('admin_id',$admin_id)->select('node_id')->get();
       $arr = array();
        foreach ($node_id as $key => $value) {
              $arr[]=$value->node_id;
        }
        foreach ($nodelist as $key => $value) {
            if(in_array($value['node_id'],$arr)){
                $nodelist[$key]['checked']=1;
            }else{
                $nodelist[$key]['checked']=0;
            }
        }
        $nodelist=$this->getChilds($nodelist);
        return $nodelist;
   }

   //取得父子结构的数据
   function getChilds($data,$pid=0){
      $arr=array();
      foreach($data as $key=>$val){
        if($val['pid']==$pid){
          $child=$this->getChilds($data,$val['node_id']);
          if($child){
            $val['child']=$child;
          }
          $arr[]=$val;
        }
      }
      return $arr;
   }

   //获取单条
   public function getOne($admin_id){
      return DB::table('admin')->where('admin_id',$admin_id)->first();
   }

   //添加权限
   public function AddNode($data){
    // print_r($data);die;
      if(!empty($data['node_id'])){
        $NodeList =array();
        foreach ($data['node_id'] as $key => $value) {
            $NodeList[$key]['admin_id'] = $data['admin_id'];
            $NodeList[$key]['node_id'] = $value;
        }
        // print_r($NodeList);
        DB::table('admin_node')->where('admin_id',$data['admin_id'])->delete();
       return  DB::table('admin_node')->insert($NodeList);
      }else{
        // echo 1;
          return DB::table('admin_node')->where('admin_id',$data['admin_id'])->delete();
      }

   }
}
